package com.easychat.test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketServer {
    public static void main(String[] args) {

        //ServerSocket是等待客户端的请求，一旦与客户段通信，就创建一个Socket对象，
        ServerSocket server = null;
        Map<String, Socket> ClientMap = new HashMap<>();
        try {
            //创建一个ServerSocket对象，指定端口为1024
            server = new ServerSocket(1024);
            System.out.println("服务已启动，等待客户端连接");
            while(true){
                //Socket用于发送和接收字节流
                Socket socket = server.accept();
                //获取端口地址
                String ip = socket.getInetAddress().getHostAddress();
                System.out.println("有客户端连接ip" + ip + ",端口：" + socket.getPort());
                String clientkey = ip+socket.getPort();
                ClientMap.put(clientkey,socket);
                //创建一个新线程接收消息
                new Thread(() -> {
                    while (true) {
                        try {
                            //从socket对象中获取输入流
                            InputStream inputStream = socket.getInputStream();
                            //字符流读取器，指定字符编码为 "UTF-8"
                            InputStreamReader inreader = new InputStreamReader(inputStream, "UTF-8");
                            //创建缓冲读取器，提高读取效率
                            BufferedReader bufferedReader = new BufferedReader(inreader);
                            //读取数据
                            String readData = bufferedReader.readLine();
                            System.out.println("收到客户端消息->" + readData);
                            ClientMap.forEach((k,v)->{
                                try {
                                    OutputStream outputStream = v.getOutputStream();
                                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                                    writer.println(socket.getPort() + ":" + readData);
                                    writer.flush();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            });



                        } catch (Exception e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }).start();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
